
import java.io.IOException;

import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.io.BufferedReader;
import java_cup.runtime.Scanner;
import cup.* ;

import command.*;

public class ProcessThread extends Thread{
   private Socket socket;
   private PrintWriter out ;
   private BufferedReader in ;
   private SoloCommandScanner parser;


   static int t=0;
   int mt=0;

   public ProcessThread(Socket socket)
   {
      super("ProcessThread");
      this.socket = socket;

      
     // TODO: handle the time out.
      
      try{
      this.socket.setSoTimeout(5000);
      }
      catch(SocketException e){
         System.err.println("WARNING: unable to set socket timeout : " + e.getMessage());
         e.printStackTrace();
      }
      
      

      try{
         out = new PrintWriter(socket.getOutputStream(), true);
         in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      }
      catch(IOException e){
         System.out.println("Can't create I/O.");
         e.printStackTrace();
      }
      
      
      parser = new SoloCommandScanner(in);
      mt = t++;
   }

   
   public void run() {
      System.out.println("INFO: "+mt+" reading ");
      
      try{
         while(true){
            Command command = parser.yylex();
            command.setIp(socket.getInetAddress());
            command.run();
            System.out.println("> " +command.getSresponse());
            out.print(command.getSresponse());
            out.flush();

            if(false)
               break;
         }
      }
      catch(java.io.EOFException e){
    	  //endOfconnection    	  
      }
      catch(java.net.SocketTimeoutException e){
    	  
      }

      catch(Exception e){
    	  e.printStackTrace();
    	  System.out.println(parser.yytext());
      }
      finally{
    	  try{
    	  socket.close();
    	  }
    	  catch(IOException e){e.printStackTrace();}
      }
      
      System.out.println("INFO: "+mt+" read");
   }
}
